package com.web.exiaodao.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.exiaodao.business.entity.CheckInRule;
import com.web.exiaodao.business.repository.CheckInRuleRepository;
import com.web.exiaodao.business.service.CheckInRuleService;
import com.web.exiaodao.remote.vo.CheckInRuleVo;

@Service("CheckInRuleService")
@Transactional(readOnly = false)
public class CheckInRuleServiceImpl extends BaseService<CheckInRule> implements CheckInRuleService {

	private static final Logger LOGGER = Logger.getLogger(CheckInRuleServiceImpl.class);

	@Autowired
	private CheckInRuleRepository checkInRuleRepository;
	
	/**
	 * 查询单条CheckInRule信息
	 * //@param tId
	 * @return 返回单个CheckInRule对象
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<CheckInRule> findOne(Long modelId) throws BusinessException {
		CheckInRule obj = new CheckInRule();
		if(modelId != 0){
			obj = checkInRuleRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
		}
		XaResult<CheckInRule> xr = new XaResult<CheckInRule>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(obj);
			LOGGER.info("后台----->查询单个实体----->CheckInRule");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	/**
	 * 分页查询状态非status的CheckInRule数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象CheckInRule集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<CheckInRule>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<CheckInRule> page = checkInRuleRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), CheckInRule.class), pageable);
		XaResult<Page<CheckInRule>> xr = new XaResult<Page<CheckInRule>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态不等于）----->CheckInRule");
		return xr;
	}

	/**
	 * 分页查询状态status的CheckInRule数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象CheckInRule集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<CheckInRule>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<CheckInRule> page = checkInRuleRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), CheckInRule.class), pageable);
		XaResult<Page<CheckInRule>> xr = new XaResult<Page<CheckInRule>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态等于）----->CheckInRule");
		return xr;
	}

	/**
	 * 保存CheckInRule信息
	 * @param model
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<CheckInRule> saveOrUpdate(CheckInRule model) throws BusinessException {
		CheckInRule obj = null;
		if(XaUtil.isNotEmpty(model.getId())){
			obj = checkInRuleRepository.findOne(model.getId());
		}else{
			obj = new CheckInRule();
		}
	    obj.setRule_title(XaUtil.isNotEmpty(model.getRule_title()) ? model.getRule_title() : obj.getRule_title());
	    obj.setContent(XaUtil.isNotEmpty(model.getContent()) ? model.getContent() : obj.getContent());
	    obj.setConsumeOrMakeMoney(XaUtil.isNotEmpty(model.getConsumeOrMakeMoney()) ? model.getConsumeOrMakeMoney() : obj.getConsumeOrMakeMoney());
		obj = checkInRuleRepository.save(obj);
		XaResult<CheckInRule> xr = new XaResult<CheckInRule>();
		xr.setObject(obj);
		LOGGER.info("后台新增或编辑数据成功！");
		return xr;
	}

	/**
	 * 修改CheckInRule状态，可一次修改多条   3删除  -1锁定  1正常
	 * //@param userId
	 * @param modelIds
	 * @param status
	 * @return 返回CheckInRule对象
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<CheckInRule> multiOperate(
			String modelIds,Integer status) throws BusinessException {
		XaResult<CheckInRule> xr = new XaResult<CheckInRule>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				CheckInRule obj = checkInRuleRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = checkInRuleRepository.save(obj);
				}
			}
		}
		LOGGER.info("批量修改数据状态成功！");
		return xr;
	}

	/**
	 * 分页查询CheckInTable
	 */
	@Override
	public XaResult<Page<CheckInRuleVo>> findCheckInRuleList(Integer nextPage,
			Integer pageSize, Map<String, Object> filterParams)
			throws BusinessException {
//		SELECT id,rule_title,content,consume_or_make_money,create_time FROM `tb_xa_checkinrule` WHERE STATUS<> 3 ORDER BY create_time
		StringBuffer sql=new StringBuffer("SELECT id,rule_title,content,consume_or_make_money,create_time ");
		sql.append("FROM `tb_xa_checkinrule` ");
		sql.append(" WHERE status<>").append(XaConstant.Status.delete);
		//统计数据库中数据个数
		StringBuffer sql1=new StringBuffer("SELECT COUNT(*) ");
		sql1.append("FROM `tb_xa_checkinrule` ");
		sql1.append(" WHERE status<>").append(XaConstant.Status.delete);
		//查询条件
		if(XaUtil.isNotEmpty(filterParams.get("LIKE_ruleTitle"))){
			sql.append(" AND rule_title ").append(" like '%").append(filterParams.get("LIKE_ruleTitle")).append("%' ");
			sql1.append(" AND rule_title ").append(" like '%").append(filterParams.get("LIKE_ruleTitle")).append("%' ");
		}
		if(XaUtil.isNotEmpty(filterParams.get("EQ_consumeOrMakeMoney"))){
			sql.append(" AND consume_or_make_money= ").append(filterParams.get("EQ_consumeOrMakeMoney")).append(" ");
			sql1.append(" AND consume_or_make_money= ").append(filterParams.get("EQ_consumeOrMakeMoney")).append(" ");
		}
		sql.append(" ORDER BY create_time DESC");
		sql1.append(" ORDER BY create_time DESC");
		List<Object[]> objs=this.query(sql.toString(), nextPage*pageSize, pageSize);
		List<CheckInRuleVo> vos=new ArrayList<CheckInRuleVo>();
		for (Object[] obj : objs) {	
			CheckInRuleVo vo = new CheckInRuleVo();
			vo.setId(Long.valueOf(obj[0].toString()));
			vo.setRule_title(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
			vo.setContent(XaUtil.isEmpty(obj[2])?"":obj[2].toString());
			vo.setConsumeOrMakeMoney(XaUtil.isEmpty(obj[3])?0:Integer.valueOf(obj[3].toString()));
			vo.setCreateTime(XaUtil.isEmpty(obj[4])?"":obj[4].toString());
			vos.add(vo);
		}
		//执行查询语句
		List<Object[]> obj1=this.query(sql1.toString(), null, null);
		//将得到的查询结果强转成int类型
		int count=Integer.parseInt(obj1.get(0)+"");				
		//调用分页
		Page<CheckInRuleVo> page= new MyPage<CheckInRuleVo>(nextPage.intValue(),pageSize.intValue(),vos,count);
		//创建结果集对象xr
		XaResult<Page<CheckInRuleVo>> xr=new XaResult<Page<CheckInRuleVo>>();
		//将page放入xr
		xr.setObject(page);
		return xr;
	}
	
}
